import { FC, useState, isValidElement, cloneElement, useMemo, useContext, useRef } from 'react';
import classnames from 'classnames';
import { PreviewProps } from './interface';

import './style/index.less';

import {
  RotateLeftOutlined,
  RotateRightOutlined,
  LeftOutlined,
  RightOutlined,
  PrinterOutlined,
} from '@ant-design/icons';
import ImgViewContext from '@/biz-components/img-view/context';
import ReactToPrint from 'react-to-print';

const Preview: FC<PreviewProps> = ({ images, extraTools }) => {
  const printContentRef = useRef<any>();
  const imgRef = useRef<any>();
  const imgBoxRef = useRef<any>();
  const prefixCls = 'image-preview';

  const [rotate, setRotate] = useState(0);

  const { currentIndex, prevFn, nextFn } = useContext(ImgViewContext);

  const { src: combinationSrc, alt } = useMemo(() => {
    const record = images[currentIndex];

    if (record) {
      return typeof record === 'string' ? { src: record, alt: '' } : record;
    }

    return  { src: "", alt: '' }

  }, [currentIndex, images]);

  const handleRotateRight = () => {
    setRotate((value) => value + 90);
  };

  const handleRotateLeft = () => {
    setRotate((value) => value - 90);
  };

  const toolClassName = `${prefixCls}-operations-operation`;
  const iconClassName = `${prefixCls}-operations-icon`;
  const tools = (extraTools || []).concat([
    {
      icon: <RotateRightOutlined />,
      onClick: handleRotateRight,
    },
    {
      icon: <RotateLeftOutlined />,
      onClick: handleRotateLeft,
    },
    // {
    //   icon: <PrinterOutlined />,
    //   onClick: printImg,
    // },
  ]);

  const { length } = images;

  const { lastIndex, showLeftOrRightSwitches } = useMemo(() => {
    return {
      lastIndex: length - 1,
      showLeftOrRightSwitches: length > 1,
    };
  }, [length]);

  const getDeg = (value,flag) => {
    let imgWidth = imgRef.current?.offsetWidth;
    let imgHeight = imgRef.current?.offsetHeight;
    setTimeout(()=>{
      imgWidth = imgRef.current?.offsetWidth;
      imgHeight = imgRef.current?.offsetHeight;
      if (value === 0) {
        if (imgBoxRef.current){
          imgBoxRef.current.style.paddingTop = 0;
          imgBoxRef.current.style.paddingLeft = 0;
        }
        return flag === '1'?'100%':'100%'
      }else
      if (value%180 === 0){
        imgBoxRef.current.style.paddingTop = 0;
        imgBoxRef.current.style.paddingLeft = 0;
        return flag === '1'?'100%':'100%'
      }else{
        if (imgHeight > imgWidth) {
          imgBoxRef.current.style.paddingTop = 0;
          imgBoxRef.current.style.paddingLeft = (imgHeight-imgWidth)/2 + 10 + 'px';
          return flag === '1'?'100%':'100%'
        }else{
          imgBoxRef.current.style.paddingTop = (imgWidth-imgHeight)/2 + 10 + 'px';
          imgBoxRef.current.style.paddingLeft = 0;
          return flag === '1'?'100%':'100%'
        }
      }
    },500)
  }

  return (
    <>
      <ul className={`${prefixCls}-operations`}>
        {tools.map(({ icon, onClick }) => (
          <li className={classnames(toolClassName)} onClick={onClick}>
            {isValidElement(icon)
              ? cloneElement(icon, {
                  className: iconClassName,
                })
              : icon}
          </li>
        ))}
        <ReactToPrint
          documentTitle="打印"
          trigger={() => <li className={classnames(toolClassName)}>{<PrinterOutlined className={classnames(iconClassName)}/>}</li>}
          content={() => printContentRef.current}
        />
      </ul>
      <div className={classnames(`${prefixCls}-img-wrapper`, 'flex-center')} ref={(el) => (imgBoxRef.current = el)}>
        <img
          ref={(el) => (imgRef.current = el)}
          className={`${prefixCls}-img`}
          src={combinationSrc}
          alt={alt}
          style={{
            transform: `scale3d(1, 1, 1) rotate(${rotate}deg)`,maxWidth: getDeg(rotate,'1'),maxHeight: getDeg(rotate,'2'),
          }}
        />
      </div>
      <div style={{ display: 'none' }}>
        <div ref={(el) => (printContentRef.current = el)}>
          <img
            className={`${prefixCls}-img`}
            src={combinationSrc}
            alt={alt}
            style={{
              transform: `scale3d(1, 1, 1) rotate(${rotate}deg)`,
              margin: '0 auto',
              display:'block'
            }}
          />
        </div>
      </div>
      {showLeftOrRightSwitches && (
        <div
          className={classnames(`${prefixCls}-switch-left`, {
            [`${prefixCls}-switch-left-disabled`]: currentIndex === 0,
          })}
          onClick={prevFn}
        >
          <LeftOutlined />
        </div>
      )}
      {showLeftOrRightSwitches && (
        <div
          className={classnames(`${prefixCls}-switch-right`, {
            [`${prefixCls}-switch-right-disabled`]: currentIndex === lastIndex,
          })}
          onClick={nextFn}
        >
          <RightOutlined />
        </div>
      )}
    </>
  );
};

export default Preview;
